package com.example.demo.juc.lock;

import java.util.concurrent.Semaphore;

/**
 * @Author: xiatian
 * @CreateTime: 2021/9/16 6:48 下午
 * @Description:
 */
public class UsualSemaphoreSample {

    public static void main(String[] args) {
        System.out.println("Action...Go!");
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new SemaphoreWorker(semaphore));
            thread.start();
        }
    }


    static class SemaphoreWorker implements Runnable {
        private String name;
        private Semaphore semaphore;

        public SemaphoreWorker(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            log("is waiting for a permit !");
            try {
                semaphore.acquire();
                log("acquired a permit!");
                log("executed!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                log("relased a permit!");
                semaphore.release();
            }
        }


        private void log(String msg) {
            if (null == name) {
                name = Thread.currentThread().getName();
            }
            System.out.println(name + " " + msg);
        }
    }


}
